package com.zzyl.serve.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.WechatUtil;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.serve.dto.MemberLoginDto;
import com.zzyl.serve.vo.MemberLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.FamilyMemberMapper;
import com.zzyl.serve.domain.FamilyMember;
import com.zzyl.serve.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 * 
 * @author chenbw
 * @date 2025-08-21
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private WechatUtil wechatUtil;
    private static final List<String> nickNamePool = List.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    @Override
    public MemberLoginVo login(MemberLoginDto dto) {
        //访问微信平台，获取用户的openId
        String openid = wechatUtil.getOpenid(dto.getCode());
        //根据openid查询此微信用户
        LambdaQueryWrapper<FamilyMember> queryWrapper = Wrappers.<FamilyMember>lambdaQuery()
                .eq(FamilyMember::getOpenId,openid);
        FamilyMember familyMember = getOne(queryWrapper);

        //访问微信平台，获取用户的手机号
        String phone = wechatUtil.getPhone(dto.getPhoneCode());
        //如果找不到，那就是第一次找那么就创建用户。如果找到了就代表当前用户之前就访问过
        if(familyMember == null){
            String nickName = nickNamePool.get((int) (Math.random() * nickNamePool.size())) + phone.substring(7);
            familyMember = FamilyMember.builder().openId(openid).phone(phone).name(nickName).build();
            save(familyMember);
        } else if (ObjectUtil.notEqual(phone,familyMember.getPhone())) {
            //否则，如果提交的手机号码与数据库中的不同，则更新数据库中的手机号码
            familyMember.setPhone( phone);
            updateById(familyMember);
        }

        //准备返回值
        MemberLoginVo vo = new MemberLoginVo();
        vo.setNickName(familyMember.getName());

        Map<String,Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName",familyMember.getName());
        vo.setToken(tokenService.createToken(claims));
        return vo;
    }
}
